import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:gold/app/user_provider.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_login.dart';
import 'package:gold/http/apis.dart';
import 'package:gold/http/http.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:gold/utils/xfg_utils.dart';
import 'package:gold/widgets/common_widgets.dart';

/// @description:
/// @author tangzhentao
/// @created at 21:12 2025/1/1

class AvatarViewmodel extends Viewmodel {
  /// 上传头像
  Future uploadAvatar() async {
    final result = await pickPhoto(max: 1);
    if (result?.isNotEmpty == true) {
      '加载中...'.loading();
      final data = await compressImage(await result!.first.readAsBytes());
      final file = MultipartFile.fromBytes(data, filename: '${DateTime.now().millisecondsSinceEpoch}.png');
      final formData = FormData.fromMap({'file' : file});
      final uploadResult = await Http().uploadImage<String>(Apis.upload, formData, showErrorMsg: false);
      if (uploadResult.success) {
        if (uploadResult.data?.isNotEmpty == true) {
          final modifyResult = await Http().request<int>(ApiLogin.completeProfile, data: {'avatar': uploadResult.data!}, showErrorMsg: false);
          EasyLoading.dismiss();
          if (modifyResult.success) {
            '修改成功~'.success();
            await XfgNav.read<UserProvider>().updateProfile();
            XfgNav.pop();
          } else {
            modifyResult.msg.error();
          }
        } else {
          EasyLoading.dismiss();
          '头像为空'.error();
        }
      } else {
        EasyLoading.dismiss();
        uploadResult.msg.error();
      }
    }
  }
}
